﻿package com.badibadi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.location.core.GeoPoint;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.AMap.OnMapClickListener;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.badibadi.adapter.AddingRecordNewAdapter;
import com.badibadi.adapter.AlbumAdapter;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.ImgInfoModel;
import com.badibadi.infos.ListsModel;
import com.badibadi.infos.MyFriendsModel;
import com.badibadi.infos.Results;
import com.badibadi.maputil.AMapUtil;
import com.badibadi.maputil.ToastUtil;
import com.badibadi.mytools.AMapUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.FriendsTool;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;
//import com.lidroid.xutils.util.LogUtils;

import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 修改图片讯息 还差@好友 onClick finish participator modified_searchText ll
 * 
 * @author Administrator
 * 
 *         array ('c_uid' => 2, //俱乐部管理员ID（当图片为俱乐部图片时，否则为0.或不传） 'id' => 23,
 *         //修改的图片id 'uid'=>3, //拥有者id, 'club_id' => '0',
 *         //照片所属俱乐部ID（不是俱乐部图片则为0.或不传） 'photo_id'=>'', //聚乐板id 'title' =>
 *         "图片名称", //聚乐板id 'address' =>'上海' , //地址 'map_x' =>"34.765515" , //纬度
 *         'map_y' => "113.753602", //经度 'typeid' => '101,103,105', //图片的类型标签
 *         最少一个 最多五个 'participator' => '@毛驴 @谢谢你的爱', //@好友---这里@后面接用户昵称
 *         'attachment' => '来源', //来源 'is_show' => '0'); //显示在动态 0:否，1：是
 * 
 * 
 * 
 *         spinner_userPhoto up_pictures_addfriends_list_1
 *         up_pictures_addfriends_list_1
 */
public class ModifiedImageInformationActivity extends BaseActivity implements
		OnClickListener, LocationSource, AMapLocationListener,
		OnGeocodeSearchListener, TextWatcher, OnMapClickListener {
	private String type = "tupian";
	private String TAG = "ModifiedImageInformationActivity";
	private GridView mGridView;
	private AddingRecordNewAdapter arnAdapter;
	private Map<Integer, String> TitleMap;
	private ArrayList<String> strings;
	private List<MyFriendsModel> listObj_main;
	private Friend_Item_Adapter friend_Item_Adapter;
	private Gallery up_pictures_addfriends_list_1;

	// 下面是地图的
	private AMap aMap;
	private MapView mapView;
	private OnLocationChangedListener mListener;
	private LocationManagerProxy mAMapLocationManager;
	private GeoPoint geoPoint;
	private boolean isFirstCallBack = false;// 是否为第一次回调

	// 发源地
	private AutoCompleteTextView searchText;
	private ProgressDialog progDialog = null;
	private GeocodeSearch geocoderSearch;
	private Marker geoMarker;
	private Marker regeoMarker;
	private Spinner spinner_userPhoto;
	private AlbumAdapter albumadapter;
	private List<ClueTypeModel> models;
	// 这里保存要上传的地址名
	private String addressName;
	// 这里保存要上传的经纬度
	private LatLonPoint latLonPoint = new LatLonPoint(40.003662, 116.465271);

	private String uid;

	private ListsModel listsModel;
	// 要传入的数据
	private String imgId = "2";// 图片id
	// private String c_uid;// 俱乐部管理员的id

	private ImgInfoModel imgInfo;// 图片信息
	// spinner_userPhoto //相册
	private EditText title;// 图片名称
	// searchText //查询文本
	private EditText attachment;// 来源
	// 是否显示在我的动态
	private CheckBox is_show;// 是否显示在我的动态

	private EditText participator;// 图片参与者

	//
	// 获取图片信息
	Results results;
	// 修改
	Results results2;

	private boolean is_activity_photo = false;// 是否是活动图片
	// spinner
	// private boolean spinner_finish = false;// spinner更新是否完成
	// private boolean title_finish = false;// 标签类别更新是否完成
	boolean isRun = true;
	private Button finish;
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(ModifiedImageInformationActivity.this);
				try {
					Utils.showMessage(ModifiedImageInformationActivity.this,
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:// 标签更新
				Utils.ExitPrgress(ModifiedImageInformationActivity.this);
				arnAdapter = new AddingRecordNewAdapter(
						ModifiedImageInformationActivity.this,
						listsModel.getLists());
				mGridView.setAdapter(arnAdapter);

				// title_finish = true;
				break;
			case 3:
				Utils.ExitPrgress(ModifiedImageInformationActivity.this);
				try {
					Utils.showMessage(ModifiedImageInformationActivity.this,
							getResources().getString(R.string.SystemError));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4:// 更新spinner
				Utils.ExitPrgress(ModifiedImageInformationActivity.this);
				albumadapter = new AlbumAdapter(models, getApplicationContext());
				spinner_userPhoto.setAdapter(albumadapter);
				// spinner_finish = true;// spinner更新完成
				try {
					initView();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 5:
				Utils.ExitPrgress(ModifiedImageInformationActivity.this);
				try {
					Utils.showMessage(ModifiedImageInformationActivity.this,
							getResources().getString(R.string.SystemError));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 6:// 获取数据完成后
					// try {
					// initView();
					// } catch (Exception e) {
					// // TODO: handle exception
					// }

				try {
					if (imgInfo != null) {
						// 这里判断是否是俱乐部的图片
						if (imgInfo.getClub_id() != null) {
							if (!imgInfo.getClub_id().equals("0")) {// 如果是俱乐部的图片
								user_photo_club(imgInfo.getClub_id());
							} else {
								user_photo();
							}
						} else {
							user_photo();
						}
					}

				} catch (Exception e) {
					// TODO: handle exception
				}

				// Utils.ExitPrgress(ModifiedImageInformationActivity.this);
				break;

			case 7:// 修改图片数据完成后
				Utils.ExitPrgress(ModifiedImageInformationActivity.this);
				if (results2 != null) {
					if (results2.isRet() == true) {
						Utils.showMessage(
								ModifiedImageInformationActivity.this,
								getResources().getString(R.string.l_xb94));
						Constants.is_shuaxin_picturePreview = true;
						Constants.is_shuaxin = true;
						ModifiedImageInformationActivity.this.finish();
					} else {
						Utils.showMessage(
								ModifiedImageInformationActivity.this,
								getResources().getString(R.string.l_xb95));
					}

				}
				break;
			case 8:// 设为头像

				break;
			case 9:// 可见
				ModifiedImageInformationActivity.this.findViewById(R.id.ll)
						.setVisibility(View.VISIBLE);

				break;
			case 10:// 不可见
				ModifiedImageInformationActivity.this.findViewById(R.id.ll)
						.setVisibility(View.GONE);
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.activity_modified_image_information);
		uid = Utils.getUid(ModifiedImageInformationActivity.this);
		Constants.is_shuaxin_picturePreview = false;
		Constants.is_shuaxin = false;
		// c_uid = getIntent().getStringExtra("c_uid");
		// if (c_uid == null) {
		// c_uid = "0";
		// }
		ModifiedImageInformationActivity.this.findViewById(R.id.ll)
				.setVisibility(View.GONE);
		// 图片的id
		imgId = getIntent().getStringExtra("imgId");

		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		init();
		// // 更新spinner信息
		// user_photo();
		// 更新照片信息
		initphotoInfo();
	}

	private void init() {
		// TODO Auto-generated method stub
		// 创建聚乐板
		this.findViewById(R.id.createPoly).setOnClickListener(
				ModifiedImageInformationActivity.this);
		this.findViewById(R.id.return_btn).setOnClickListener(
				ModifiedImageInformationActivity.this);
		is_show = (CheckBox) this.findViewById(R.id.is_show);
		finish = (Button) this.findViewById(R.id.finish);
		finish.setOnClickListener(this);
		// participator = (EditText) this.findViewById(R.id.participator);
		attachment = (EditText) this.findViewById(R.id.attachment);
		title = (EditText) this.findViewById(R.id.title);
		spinner_userPhoto = (Spinner) this.findViewById(R.id.spinner_userPhoto);
		strings = getIntent().getStringArrayListExtra("files");
		mGridView = (GridView) this.findViewById(R.id.xiugai_picture_gridView);
		listObj_main = new ArrayList<MyFriendsModel>();
		up_pictures_addfriends_list_1 = (Gallery) findViewById(R.id.up_pictures_addfriends_list_1);
		friend_Item_Adapter = new Friend_Item_Adapter(
				ModifiedImageInformationActivity.this);
		up_pictures_addfriends_list_1.setAdapter(friend_Item_Adapter);
		Interest();

		mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				// TODO Auto-generated method stub
				if (arnAdapter.getIsItemClick(position) == true) {
					arnAdapter.setIsItemClick(position);
					arnAdapter.notifyDataSetInvalidated();

				} else if (arnAdapter.getSelectNumber() >= arnAdapter
						.getUpperLimit()) {
					ShowToast(ModifiedImageInformationActivity.this,
							getResources().getString(R.string.l_xb4)
									+ arnAdapter.getUpperLimit()
									+ getResources().getString(R.string.l_xb5));
				} else {
					arnAdapter.setIsItemClick(position);
					arnAdapter.notifyDataSetInvalidated();
				}
				// 提交只需要提交TitleMap中的数据即可
				TitleMap = arnAdapter.getTitleMap();
			}
		});
		this.findViewById(R.id.modified_dingwei).setOnClickListener(this);
		this.findViewById(R.id.at_friends).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(
								ModifiedImageInformationActivity.this,
								MyFriendsResultActivity.class);
						startActivityForResult(intent, 3);
					}
				});

		searchText = (AutoCompleteTextView) this
				.findViewById(R.id.modified_searchText);
		searchText.addTextChangedListener(this);

		progDialog = new ProgressDialog(this);
		geocoderSearch = new GeocodeSearch(this);
		geocoderSearch.setOnGeocodeSearchListener(this);

		if (aMap == null) {
			aMap = mapView.getMap();
			geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
					.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
			regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
					.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

			setUpMap();
		}

	}

	// 初始化视图
	protected void initView() {
		// TODO Auto-generated method stub
//		   
		// 判断经纬度是否合法
		if (imgInfo.getMap_x() != null && imgInfo.getMap_y() != null) {
			// 如果经纬度合法
			if (AMapUtils.LatitudeAndLongItudeIsLegal(
					Double.parseDouble(imgInfo.getMap_x()),
					Double.parseDouble(imgInfo.getMap_y()))) {
//				   
				latLonPoint = new LatLonPoint(Double.parseDouble(imgInfo
						.getMap_x()), Double.parseDouble(imgInfo.getMap_y()));
				getAddress(latLonPoint);

				AMapUtils.drawMarker(aMap, "", "",
						AMapUtil.convertToLatLng(latLonPoint));
				AMapUtils.CameraMoveTo(aMap,
						AMapUtil.convertToLatLng(latLonPoint));
				isFirstCallBack = false;
			} else {
//				   
				isFirstCallBack = true;
				Utils.showMessage(this,
						getResources().getString(R.string.l_xb96));
			}
		} else {
//			   
			isFirstCallBack = true;
			Utils.showMessage(this, getResources().getString(R.string.l_xb96));
		}

		if (imgInfo != null) {
			// 设置名字
			if (imgInfo.getTitle() != null)
				title.setText("" + imgInfo.getTitle());
			// 设置选中的id
			if (imgInfo.getTypeid() != null) {
				String[] typeid = (imgInfo.getTypeid()).split(",");
				if (typeid != null)
					for (int i = 0; i < typeid.length; i++) {
						arnAdapter.setIsItemClick_id("" + typeid[i]);

					}
				arnAdapter.notifyDataSetInvalidated();

			}

			// 来源
			if (imgInfo.getAttachment() != null) {
				attachment.setText("" + imgInfo.getAttachment());
			}

			// is_show是否显示到动态（0：否，1：是）

			if (imgInfo.getIs_show().equals("0")) {
				is_show.setChecked(false);
			} else {
				is_show.setChecked(true);
			}

			// @的好友
			if (!StringUtil.isNullOrEmpty(imgInfo.getParticipator())) {
				// participator.setText("" + imgInfo.getParticipator());

				String aaa = imgInfo.getParticipator().substring(1);
				String bbb[] = aaa.split("@");

//				for (int i = 0; i < bbb.length; i++) {
//					   
//				}
				for (int i = 0; i < bbb.length; i++) {
					MyFriendsModel fr = new MyFriendsModel();
					fr.setJudge(true);
					fr.setNickName(bbb[i]);
					listObj_main.add(fr);
					// if (listObj_main.size() > 0 && listObj_main.size() >= 3)
					// {
					// up_pictures_addfriends_list_1.setSelection(listObj_main
					// .size() / 2 + 1);
					// } else if (listObj_main.size() > 0
					// && listObj_main.size() == 2) {
					// up_pictures_addfriends_list_1.setSelection(1);
					// }
				}
				friend_Item_Adapter.notifyDataSetChanged();
			}

//			   
			// 初始化为默认的相册名
			for (int i = 0; i < models.size(); i++) {
				if (models.get(i).getId().equals(imgInfo.getPhoto_id())) {

					spinner_userPhoto.setSelection(i);
					break;
				}
			}
			// 更新标签
			TitleMap = arnAdapter.getTitleMap();
			// spinner
			// for(int i=0;i)
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		/**
		 * at好友
		 */
		if (requestCode == 3 && resultCode == 3) {
//			   ("进入");
			// et_sendDynamic.setText(et_sendDynamic.getText().toString()+data.getStringExtra("result"));
			List<MyFriendsModel> listObj = (ArrayList<MyFriendsModel>) data
					.getSerializableExtra("result");
			// for (int i = 0; i < listObj.size(); i++) {
			//    ("@好友数据:" + listObj.get(i).toString());
			// }
			for (int i = 0; i < listObj.size(); i++) {
				if (listObj.get(i).isJudge()) {
					listObj_main.add(listObj.get(i));
				}
			}
			if (listObj_main.size() > 0 && listObj_main.size() >= 3) {
				up_pictures_addfriends_list_1
						.setSelection(listObj_main.size() / 2 + 1);
			} else if (listObj_main.size() > 0 && listObj_main.size() == 2) {
				up_pictures_addfriends_list_1.setSelection(1);
			}
			friend_Item_Adapter.notifyDataSetChanged();
			//    ("我是回传数据" + listObj.get(0).getNickName());

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 获取图片信息
	 */
	private void initphotoInfo() {
		// TODO Auto-generated method stub
		// imgInfo
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				// list= new ArrayList<Pre_message_total>();

				String languageType = Dialog
						.getSystemLanguageType(ModifiedImageInformationActivity.this);
				String content = Utils.getRequest(Constants.BadiUrl_1
						+ "photo/imgInfo?imgId=" + imgId + "&languageType="
						+ languageType);
//				LogUtils.d(Constants.BadiUrl_1 + "photo/imgInfo?imgId=" + imgId
//						+ "&languageType=" + languageType);
				// String invite_content = Utils.sendRequest(map,
				// Constants.BadiUrl + "message_total");
				//    
				if (content != null) {
					results = Utils.checkResult_NNN(
							ModifiedImageInformationActivity.this, content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   
						try {
							imgInfo = JSONUtils.getEntityByJsonString(
									results.getRetmsg(), ImgInfoModel.class);

							handler.sendEmptyMessage(6);

						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {

						handler.sendEmptyMessage(5);
					}
				} else {

					handler.sendEmptyMessage(1);
				}

			}
		});
	}

	/**
	 * 获取spinner的数据
	 */
	private void user_photo() {
		ModifiedImageInformationActivity.this.findViewById(R.id.ll)
				.setVisibility(View.VISIBLE);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// Map<String, Object> map = new HashMap<String, Object>();
				// map.put("uid", "1");

				String content = Utils.getRequest(Constants.BadiUrl
						+ "user_photo?uid=" + uid);
				if (content != null) {
					//    ("结果是:" + content);
					Results results = Utils.checkResult_NNN(
							getApplicationContext(), content);
					if (results != null && results.getRetmsg() != null) {
//						   
						//    ("得到的结果是：" + results.getRetmsg());
						try {
							models = JSONUtils.getListByJsonString(
									results.getRetmsg(), ClueTypeModel.class);
							handler.sendEmptyMessage(4);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void user_photo_club(final String club_id) {
		Utils.showPrgress(ModifiedImageInformationActivity.this);
		if (imgInfo.getActivity_id() != null) {
			if (!imgInfo.getActivity_id().equals("0")) {

				handler.sendEmptyMessage(10);
				// ModifiedImageInformationActivity.this.findViewById(R.id.ll).setVisibility(View.GONE);
			} else {

				handler.sendEmptyMessage(9);
				// ModifiedImageInformationActivity.this.findViewById(R.id.ll).setVisibility(View.VISIBLE);
			}
		} else {

			handler.sendEmptyMessage(9);
			// ModifiedImageInformationActivity.this.findViewById(R.id.ll).setVisibility(View.VISIBLE);
		}
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", "2");
				map.put("cid", club_id);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "club/photoList");
				if (content != null) {
//					   ("俱乐部的聚乐版返回结果是:" + content);
					Results results = Utils.checkResult_NNN(
							getApplicationContext(), content);
					if (results != null && results.getRetmsg() != null) {
						//    ("得到的结果是：" + results.getRetmsg());
						try {
							models = JSONUtils.getListByJsonString(
									results.getRetmsg(), ClueTypeModel.class);
							handler.sendEmptyMessage(4);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	/**
	 * 我是获取兴趣爱好的
	 */
	private void Interest() {
		Utils.showPrgress(ModifiedImageInformationActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", type);
				map.put("languageType",
						Dialog.getSystemLanguageType(ModifiedImageInformationActivity.this));

				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "type/listType");
				if (content != null) {
//					   ("ttt 结果是:" + content);
					Results results = Utils.checkResult_NNN(
							getApplicationContext(), content);
					if (results != null && results.getRetmsg() != null) {
//						   
						try {
							listsModel = JSONUtils.getEntityByJsonString(
									results.getRetmsg(), ListsModel.class);
							handler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
//							   
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void setUpMap() {
		// TODO Auto-generated method stub
		aMap.moveCamera(CameraUpdateFactory
				.newLatLngZoom(Constants.CHENGDU, 12));// 设置指定的可视区域地图
		// aMap.setMyLocationStyle(myLocationStyle);
		aMap.setOnMapClickListener(this);// 点击地图上的
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	// 点击地图的上东西后回调
	@Override
	public void onMapClick(LatLng latlng) {
		// TODO Auto-generated method stub
		if (aMap != null && latlng != null) {
			aMap.clear();
			// MarkerOptions markerOptions=new MarkerOptions();
			// markerOptions.
			geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
					.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
			// aMap.addMarker(new MarkerOptions());
			geoMarker.setPosition(latlng);
			getAddress(AMapUtil.convertToLatLonPoint(latlng));
			aMap.invalidate();
			latLonPoint = AMapUtil.convertToLatLonPoint(latlng);
//			   
//					"address+====>" + addressName + " latLonPoint--->"
//							+ latLonPoint.getLatitude() + ","
//							+ latLonPoint.getLongitude());

		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	// TextWatcher

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		String newText = s.toString().trim();
		Inputtips inputTips = new Inputtips(
				ModifiedImageInformationActivity.this, new InputtipsListener() {

					@Override
					public void onGetInputtips(List<Tip> tipList, int rCode) {
						if (rCode == 0) {// 正确返回
							List<String> listString = new ArrayList<String>();
							for (int i = 0; i < tipList.size(); i++) {
								listString.add(tipList.get(i).getName());
							}
							ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(
									getApplicationContext(),
									R.layout.route_inputs, listString);
							searchText.setAdapter(aAdapter);
							aAdapter.notifyDataSetChanged();
						}
					}
				});
		try {
			inputTips.requestInputtips(newText, null);// 第一个参数表示提示关键字，第二个参数默认代表全国，也可以为城市区号

		} catch (AMapException e) {
			   
		}
	}

	/**
	 * 地理编码查询回调
	 */
	@Override
	public void onGeocodeSearched(GeocodeResult result, int rCode) {
		// // TODO Auto-generated method stub
		dismissDialog();
		if (rCode == 0) {
			if (result != null && result.getGeocodeAddressList() != null
					&& result.getGeocodeAddressList().size() > 0) {
				GeocodeAddress address = result.getGeocodeAddressList().get(0);
				aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
						AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));
				geoMarker.setPosition(AMapUtil.convertToLatLng(address
						.getLatLonPoint()));
				addressName = getResources().getString(R.string.l_xb97)
						+ address.getLatLonPoint() + "\n"
						+ getResources().getString(R.string.l_xb98)
						+ address.getFormatAddress();
				// 这里保存要上传的经纬度
				latLonPoint = address.getLatLonPoint();
//				   
//						+ "///" + latLonPoint.getLongitude());

				ShowToast(ModifiedImageInformationActivity.this, addressName);
			} else {
				ToastUtil.show(ModifiedImageInformationActivity.this,
						R.string.no_result);
			}

		} else if (rCode == 27) {
			ToastUtil.show(ModifiedImageInformationActivity.this,
					R.string.error_network);
		} else if (rCode == 32) {
			ToastUtil.show(ModifiedImageInformationActivity.this,
					R.string.error_key);
		} else {
			ToastUtil.show(ModifiedImageInformationActivity.this,
					getString(R.string.error_other) + rCode);
		}
	}

	// /**
	// * 逆地理编码回调
	// */
	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
		// // TODO Auto-generated method stub
		dismissDialog();
		if (rCode == 0) {
			if (result != null && result.getRegeocodeAddress() != null
					&& result.getRegeocodeAddress().getFormatAddress() != null) {
				addressName = result.getRegeocodeAddress().getFormatAddress()
						+ getResources().getString(R.string.l_xb99);
				if (addressName != ""
						&& searchText.getText().toString().trim() != "") {
					searchText.setText(""
							+ result.getRegeocodeAddress().getFormatAddress());
				}
				// aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
				// AMapUtil.convertToLatLng(latLonPoint), 15));
				regeoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint));
				ToastUtil.show(ModifiedImageInformationActivity.this,
						addressName);
			} else {
				ToastUtil.show(ModifiedImageInformationActivity.this,
						R.string.no_result);
			}
		} else if (rCode == 27) {
			ToastUtil.show(ModifiedImageInformationActivity.this,
					R.string.error_network);
		} else if (rCode == 32) {
			ToastUtil.show(ModifiedImageInformationActivity.this,
					R.string.error_key);
		} else {
			ToastUtil.show(ModifiedImageInformationActivity.this,
					getString(R.string.error_other) + rCode);
		}
	}

	/**
	 * 隐藏进度条对话框
	 */
	public void dismissDialog() {
		if (progDialog != null) {
			progDialog.dismiss();
		}
	}

	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation aLocation) {
		//    
		if (mListener != null && aLocation != null) {

			//    
			// "aLocation.getLatitude()--->"+aLocation.getLatitude()+"  aLocation.getLongitude()===>"+aLocation.getLongitude());
			// mListener.onLocationChanged(aLocation);// 显示系统小蓝点
			// geoPoint=new GeoPoint((int) (aLocation.getLatitude() * 1E6),
			// (int) (aLocation.getLongitude() * 1E6));
			// //用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
			// CameraUpdateFactory a=CameraUpdateFactory.newLatLngZoom(new
			// LatLng(arg0, arg1), arg1)

			if (isFirstCallBack == true) {
				aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
						aLocation.getLatitude(), aLocation.getLongitude()), 12));// 设置指定的可视区域地图
				isFirstCallBack = false;
				latLonPoint = new LatLonPoint(aLocation.getLatitude(),
						aLocation.getLongitude());
				getAddress(new LatLonPoint(aLocation.getLatitude(),
						aLocation.getLongitude()));
			}
		}
	}

	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(this);
			/*
			 * mAMapLocManager.setGpsEnable(false);
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
			 * API定位采用GPS和网络混合定位方式
			 * ，第一个参数是定位provider，第二个参数时间最短是2000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
			 */
			mAMapLocationManager.requestLocationUpdates(
					LocationProviderProxy.AMapNetwork, 2000, 10, this);
		}
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destory();
		}
		mAMapLocationManager = null;
	}

	/**
	 * 显示进度条对话框
	 */
	public void showDialog() {
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage(getResources().getString(R.string.l_xb63));
		progDialog.show();
	}

	/**
	 * 响应逆地理编码
	 */
	public void getAddress(final LatLonPoint latLonPoint) {
		showDialog();
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
				GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
		geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
	}

	/**
	 * 响应地理编码
	 */
	public void getLatlon(final String name) {
		showDialog();
		GeocodeQuery query = new GeocodeQuery(name, null);// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
		geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.modified_dingwei:
			// getAddress();
			getLatlon("" + searchText.getText().toString().trim());
			break;
			
			
		case R.id.finish:
			// spinner_userPhoto //SPINNER 聚乐板
			// spinner_userPhoto //相册
			// private EditText title;//图片名称
			// 经纬度 latLonPoint
			// 标签类别，
			// 参与者 participator
			// attachment;//来源
			// 是否显示在动态is_show

			if (!TitleMap.isEmpty()) {
				edit_img();
			} else {
				//    
				Utils.showMessage(this,
						getResources().getString(R.string.l_xb100));
			}
			break;
		case R.id.createPoly:// 创建聚乐板
			Intent intent1 = new Intent(ModifiedImageInformationActivity.this,
					CreateNewPoly1Activity.class);
			startActivity(intent1);
			ModifiedImageInformationActivity.this.finish();
			break;
		case R.id.return_btn:
			ModifiedImageInformationActivity.this.finish();
			break;
		// case R.id.SetToPortrait://设为头像
		// // <Button
		// android:id="@+id/SetToPortrait"
		// android:layout_width="wrap_content"
		// android:layout_height="wrap_content"
		// android:layout_alignParentRight="true"
		// android:layout_alignParentTop="true"
		// android:layout_marginBottom="5dp"
		// android:layout_marginRight="5dp"
		// android:layout_marginTop="5dp"
		// android:background="@drawable/shape_btn_green_button"
		// android:text="设为头像"
		// android:textColor="@color/white_f4f4f4" />
		// Utils.showMessage(getApplicationContext(), "903");
		// break;

		}
	}

	// 修改个人图片信息
	public void edit_img() {
		Utils.showPrgress(ModifiedImageInformationActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Map<String, Object> map = new HashMap<String, Object>();

				try {
					map.put("image", fengzhuang());
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					   
				}
				map.put("languageType",
						Dialog.getSystemLanguageType(ModifiedImageInformationActivity.this));

				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "photo/edit_img");
				if (content != null) {
//					   ("ttt 结果是:" + content);
					results2 = Utils.checkResult_NNN(getApplicationContext(),
							content);
					if (results2 != null && results2.getRetmsg() != null) {
//						   
						try {
							handler.sendEmptyMessage(7);
						} catch (Exception e) {
							// TODO Auto-generated catch block
//							   
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private JSONObject fengzhuang() throws JSONException {
		// TODO Auto-generated method stub
		JSONObject js = new JSONObject();
		js.put("c_uid", imgInfo.getC_uid());
		js.put("id", imgInfo.getId());
		js.put("uid", imgInfo.getUid());
		js.put("club_id", imgInfo.getClub_id());
		js.put("address", searchText.getText().toString().trim());
		if ((!imgInfo.getActivity_id().equals("0")// 如果是活动相册
				|| imgInfo.getActivity_id() != null)
				&& (imgInfo.getClub_id() != null || !imgInfo.getClub_id()
						.equals("0"))) {

			js.put("photo_id", imgInfo.getPhoto_id());
		} else// 不是活动相册
		{

			js.put("photo_id",
					""
							+ models.get(
									spinner_userPhoto.getSelectedItemPosition())
									.getId());
		}

		js.put("title", "" + title.getText().toString());
		// js.put("address", value);
		js.put("map_x", "" + latLonPoint.getLatitude());
		js.put("map_y", "" + latLonPoint.getLongitude());
		js.put("typeid", getTypeId());
		// 'attachment' => '来源', //来源
		// 'is_show' => '0'); //显示在动态 0:否，1：是
		// String content = participator.getText().toString().trim();
		// String content2 = content.replaceAll(" ", "");

		js.put("participator",
				"" + FriendsTool.BackAllResult("sdf", listObj_main));// 'participator'
																		// =>
																		// '@毛驴
																		// @谢谢你的爱',
																		// //@好友---这里@后面接用户昵称
		js.put("attachment", "" + attachment.getText().toString());
		js.put("is_show", "0");

		return js;
	}

	/**
	 * 是否被选中
	 * 
	 * @return
	 */
	private String is_show() {
		// TODO Auto-generated method stub
		if (is_show.isChecked()) {
			return "1";
		} else {
			return "0";
		}
	}

	/**
	 * 获取标签类别
	 * 
	 * @return
	 */
	public String getTypeId() {
		StringBuffer sb = new StringBuffer();

		Iterator it = TitleMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Object key = entry.getKey();
			Object value = entry.getValue();
			sb.append("," + value.toString().trim());
		}
//		   
		String a = sb.substring(1, sb.length());
//		   
		// TitleMap
		return a;
	}

	private class Friend_Item_Adapter extends BaseAdapter {
		private Context context;

		public Friend_Item_Adapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listObj_main.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return listObj_main.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			LayoutInflater inflater = LayoutInflater.from(context);
			arg1 = inflater.inflate(R.layout.friends_gallery_item, null);
			// if (!listObj_main.get(arg0).isJudge()) {
			// arg1.setVisibility(View.GONE);
			// } else {
			// arg1.setVisibility(View.VISIBLE);
			// }
			TextView gallery_item_text = (TextView) arg1
					.findViewById(R.id.gallery_item_text);
			ImageView gallery_item_cha = (ImageView) arg1
					.findViewById(R.id.gallery_item_cha);
			gallery_item_text.setText("@"
					+ listObj_main.get(arg0).getNickName());
			gallery_item_cha.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg10) {
					listObj_main.remove(arg0);
					Friend_Item_Adapter.this.notifyDataSetChanged();
				}
			});
			return arg1;
		}

	}

}
